package base.annotation.cls.track;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import base.annotation.Constraints;
import base.annotation.DBTable;
import base.annotation.SQLString;
import base.annotation.SqlInteger;

public class TableCreator {
	
	public static void main(String[] args) throws Exception{
		String className="base.annotation.database.Member";
		Class<?> cl=Class.forName(className);
		
		DBTable dbTable=cl.getAnnotation(DBTable.class);
		if(dbTable!=null){
			String tableName=dbTable.name();
			
			if(tableName.length()<1){
				tableName=cl.getName().toUpperCase();
			}
			
			List<String> columnDefs=new ArrayList<String>();
			StringBuilder createCommand=new StringBuilder("CREATE TABLE "+tableName+"(");
			
			for(Field field:cl.getDeclaredFields()){
				String columnName=null;
				Annotation[]anns=field.getDeclaredAnnotations();
				if(anns.length<1){
					continue;
				}
				
				if(anns[0] instanceof SqlInteger){
					SqlInteger sInt=(SqlInteger) anns[0];
					if(sInt.name().length()<1){
						columnName=field.getName().toUpperCase();
					}else{
						columnName=sInt.name();
					}
					columnDefs.add(columnName+" INT"+getConstraints(sInt.constraints()));
				}
				
				if(anns[0] instanceof SQLString){
					SQLString sString=(SQLString) anns[0];
					if(sString.name().length()<1){
						columnName=field.getName().toUpperCase();
					}else{
						columnName=sString.name();
					}
					columnDefs.add(columnName+" VARCHAR("+sString.value()+")"+getConstraints(sString.constraints()) );
				}
				
				
				for(String columnDef:columnDefs){
					createCommand.append("\n	"+columnDef+",");
				}
			}
			String tableCreate=createCommand.substring(0, createCommand.length()-1)+");";
			System.out.println("Table Creation sql for "+className+" is :\n"+tableCreate);
			
		}else{
			System.out.println("no DBTable annotations in class "+className);
		}
		
	}
	
	
	public static String getConstraints(Constraints con){
		String constraints="";
		if(!con.allowNull()){
			constraints+=" NOT NULL";
		}
		if(con.primaryKey()){
			constraints+=" PRIMARY KEY";
		}
		if(con.unique()){
			constraints+=" UNIQUE";
		}
		
		return constraints;
	}
}
